package com.android.often.util.animation;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class AnimationDrawableUtil1 extends ImageView {

	private AnimationDrawable animationDrawable;

	private String TAG = getClass().getSimpleName();
	
	public AnimationDrawableUtil1(Context context, int resid) {
		super(context);
		setBackgroundResource(resid);
	}

	
	public AnimationDrawableUtil1(Context context) {
		super(context);
	}
	
	public AnimationDrawableUtil1(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	@Override
	public void setBackgroundResource(int resid) {
		Log.v(TAG, "setBackgroundResource");
		super.setBackgroundResource(resid);
		stop();
		Drawable drawable = getBackground();
		if(drawable instanceof AnimationDrawable) {
			animationDrawable = (AnimationDrawable) drawable;
			setBackgroundDrawable(animationDrawable);
			setImageDrawable(animationDrawable);
		}
	}

	
	@Override
	public void setImageDrawable(Drawable drawable) {
		Log.v(TAG, "setImageDrawable");
		super.setImageDrawable(drawable);
		stop();
		if(drawable instanceof AnimationDrawable) {
			animationDrawable = (AnimationDrawable)drawable;
		}
	}
	
	@Override
	public void setImageResource(int resid) {
		Log.v(TAG, "setImageResource");
		super.setImageResource(resid);
		stop();
		Drawable drawable = getDrawable();
		if(drawable instanceof AnimationDrawable) {
			animationDrawable = (AnimationDrawable)drawable;
		}
	}
	
	public void start() {
		if (null != animationDrawable) {
			animationDrawable.start();
			Log.v(TAG, "start");
		}
	}

	public void stop() {
		if (null != animationDrawable) {
					animationDrawable.stop();
					Log.v(TAG, "stop");
		}
	}
	
	
	@Override
	public void setVisibility(int visibility) {
		Log.v(TAG, "setVisibility");
		if(View.VISIBLE == visibility) {
			start();
		} else {
			stop();
		}
		super.setVisibility(visibility);
	}
	
	public void changeResource(int resId) {
		setImageResource(resId);
		start();
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		Log.v(TAG, "onWindowFocusChanged");
		if(hasWindowFocus) {
			start();
		} else {
			stop();
		}
		super.onWindowFocusChanged(hasWindowFocus);
	}
}